<template>
  <div class="container">
    <h3>vue+openlayers: </h3>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css';
import { Map, View } from 'ol';
import Tile from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import EChartsLayer from 'ol-echarts';
export default {
  data() {
    return {
      map: null,
      chart: null,
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      let layer = new Tile({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
        })
      })
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [layer],
        view: new View({
          center: [116.397411, 39.909186],
          zoom: 7,
          projection: 'EPSG:4326'
        })
      })

      this.map.on('postcompose', evt => { // 地图渲染完成后触发
        document.querySelector('canvas').style.filter = `hue-rotate(180deg)` // 随机改变地图颜色
      })
      this.addEchartsLayer()
    },

    // 加载echarts图层
    addEchartsLayer() {
      // echarts
      if (this.chart) this.chart.dispose() && (this.chart = null) // 销毁echarts图层
      this.chart = new EChartsLayer({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/> {b} : {c} {d}%'
        },
        color: ['#c23531', '#2f4554', '#61a0a8'],
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: 20,
            coordinates: [116.397411, 39.909186],
            data: [
              { value: 335, name: '直接访问' },
              { value: 310, name: '邮件营销' },
              { value: 234, name: '联盟广告' }
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0,0,0,0.5)'
              }
            }
          }
        ]
      })
      this.chart.appendTo(this.map); // 将echarts图层添加到地图中
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 750px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 100%;
      height: 720px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>
